<template>
  <div class="product-manage" >
<!--    <el-button type="primary" @click="showAddDialog">添加商品</el-button>-->
    <el-table  highlight-current-row :data="products"  style="width: 100%">
      <el-table-column prop="cid" label="商品id" width="80" ></el-table-column>
        <el-table-column  label="商品图片">
          <template slot-scope="scope">
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.image"
            ></el-image>
          </template>
        </el-table-column>
      <el-table-column prop="cname" label="商品名称"></el-table-column>
      <el-table-column prop="cnumber" label="商品库存"></el-table-column>
      <el-table-column prop="cmessage" label="商品描述"></el-table-column>
      <el-table-column prop="price" label="商品价格（元/kg）" width="150"></el-table-column>
      <el-table-column prop="username" label="所属者"></el-table-column>
      <el-table-column prop="typename" label="一级分类"></el-table-column>
      <el-table-column prop="type" label="二级分类"></el-table-column>
      <el-table-column prop="state" label="上架状态">
        <template slot-scope="scope">
          <el-tag :type="getTagType(scope.row.state)">{{getProductState(scope.row.state)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="150" label="操作">
        <template slot="header" slot-scope="scope">
          <el-input
              v-model="search_key"
              size="mini"
              @keyup.enter.native="search"
              placeholder="输入关键字搜索"/>
        </template>
        <template slot-scope="scope">
          <el-button  size="small" type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small"  type="danger" @click="deleteProduct(scope.row,scope.$index,products)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="添加商品" :visible.sync="addDialogVisible">
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="商品名称" prop="cname">
          <el-input v-model="addForm.cname"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="addForm.category" placeholder="请选择">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="add">确认添加</el-button>
        <el-button @click="addDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑商品" :visible.sync="editDialogVisible">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="80px">
        <el-form-item label="商品名称" prop="cname">
          <el-input v-model="editForm.cname"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="editForm.category" v-on:change="getType2" placeholder="请选择一级分类">
            <el-option v-for="category in categories" :key="category.tid" :label="category.typename" :value="category.tid"></el-option>
          </el-select>

          <el-select v-model="editForm.category2" v-on:change="settypename" placeholder="请选择二级分类" >
            <el-option v-for="category in categories2" :key="category.ctid" :label="category.type" :value="category.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="edit">确认修改</el-button>
        <el-button @click="editDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'

export default {
  data() {
    return {
      search_key:'',
      products: [],
      categories: [],
      categories2: [],
      addDialogVisible: false,
      addForm: {
        cname: '',
        category: '',
        price: ''
      },
      addRules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }]
      },
      editDialogVisible: false,
      editForm: {
        cid: '',
        cname: '',
        category: '',
        category2: '',
        price: ''
      },

      editRules: {
        cname: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getProducts()
    this.getCategories()
    // this.getCategories2()

  },
  methods: {
    settypename(typename){

      this.editForm.category2=typename;
      console.log(typename)
    },
    search(){
      if (this.search_key===''){
        this.getProducts()
        this.getCategories()

      }else {
        axios.get('http://localhost:8088/commodity_b/searchCommodityByKey',{params:{
            key:this.search_key
          }})
            .then(response => {
              this.products=response.data.data
            })
            .catch(error => {
              console.log(error)
            })
      }
    },
    getTagType(value){
      if (value === 1) {
        return 'success';
      } else if (value === 0) {
        return 'warning';
      } else {
        return '';
      }
    },
    getProductState(value){
      if (value === 1) {
        return '上架中';
      } else if (value === 0) {
        return '未上架';
      } else {
        return '';
      }
    },
    getType2(tid){
      axios.get('http://localhost:8088/commodity_b/getCommodityTypesByTID',{params:{
        tid:tid
        }})
          .then(response => {
            this.editForm.category2=''
            console.log(response.data.data)
            this.categories2 = response.data.data
          })
          .catch(error => {
            console.log(error)
          })
    },
    getProducts() {
      axios.get('http://localhost:8088/commodity_b/findAllCommodity')
          .then(response => {
            console.log(response.data.data)
             this.products = response.data.data
            // this.categories=response.data.categories
          })
          .catch(error => {
            console.log(error)
          })
    },
    getCategories() {
      axios.get('http://localhost:8088/commodity_b/findAllCategories')
          .then(response => {
            this.categories = response.data.data
          })
          .catch(error => {
            console.log(error)
          })
    },
    showAddDialog() {
      this.addDialogVisible = true
    },
    add() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          axios.post('/products', this.addForm)
              .then(() => {
                this.addDialogVisible = false
                this.getProducts()
                Message.success('添加商品成功')
              })
              .catch(error => {
                console.log(error)
              })
        } else {
          return false
        }
      })
    },
    showEditDialog(product) {
      this.editForm.cid = product.cid
      this.editForm.cname = product.cname
      this.editForm.category = product.category
      this.editForm.price = product.price
      this.editForm.category=product.typename
      this.editForm.category2=product.type
      this.editDialogVisible = true
    },
    edit() {
      if (this.editForm.category2===''){
        Message.warning("请选择商品的二级分类")
        return
      }else {
        axios.get('http://localhost:8088/commodity_b/updateCommodityByCID',{
          params:{
            cid:this.editForm.cid,
            price:this.editForm.price,
            typename:this.editForm.category2
          }
        })
            .then(response => {
              this.getProducts()
              this.getCategories()
              Message.success("修改成功！")
              this.editDialogVisible=false
            })
            .catch(error => {
              console.log(error)
            })
      }

      // this.$refs.editForm.validate(valid => {
      //   if (valid) {
      //     axios.put(`/products/${this.editForm.cid}`, this.editForm)
      //         .then(() => {
      //           this.editDialogVisible = false
      //           this.getProducts()
      //           Message.success('修改商品成功')
      //         })
      //         .catch(error => {
      //           console.log(error)
      //         })
      //   } else {
      //     return false
      //   }
      // })
    },
    deleteProduct(product,index,rows) {
      MessageBox.confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            axios.delete('http://localhost:8088/commodity_b/delCommodityByCID',{params:{
                cid:product.cid
              }})
                .then(() => {
                  // this.getProducts()
                  rows.splice(index,1);
                  Message.success('删除商品成功')
                })
                .catch(error => {
                  console.log(error)
                })
          })
          .catch(() => {
            // do nothing
          })
    }
  }
}
</script>

<style scoped> .product-manage { padding: 20px; } </style>
